<?php
namespace Todo\Service;
use Todo\Util\ArrayUtil;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class UserService extends BaseService
{
    private static $__INSTANCE = null;

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new UserService();

        return self::$__INSTANCE;
    }

    /**
     * 修改密码
     * @param int $userId 用户ID
     * @param string $oldPass 原始密码
     * @param string $newPass 新密码
     * @return bool|false|int
     */
    public function changePassword($userId, $oldPass, $newPass){
        $userModel = D('Todo/Sys/User');
        $userInfo = $userModel->keyFind($userId);
        if(!$userInfo) {
            $this->setError('用户信息不存在');
            return false;
        }
        if($userInfo['password'] != LoginService::getInstance()->encrypt($oldPass, $userInfo['salt'])) {
            $this->setError('原始密码错误');
            return false;
        }
        $userInfo['password'] = LoginService::getInstance()->encrypt($newPass, $userInfo['salt']);
        return $userModel->save($userInfo);
    }

    /**
     * 重置一个用户的密码，默认是8个8
     * @param int $userId 用户ID
     * @param string $password 密码
     * @return bool
     */
    public function resetPassword($userId, $password=''){
        $userModel = D('Todo/Sys/User');
        $userInfo = $userModel->keyFind($userId);
        if(!$password) $password = md5(C('DEFAULT_PASSWORD').C('MD5_SALT'));
        $userInfo['password'] = LoginService::getInstance()->encrypt($password, $userInfo['salt']);
        return $userModel->save($userInfo);
    }

    /**
     * 更新用户信息
     * @param int $userId 用户ID
     * @param array $post 提交的用户信息
     * @return bool
     */
    public function updateInfo($userId, $post){
        $data = array(
            'nickname' => $post['nickname'],
            'email' => $post['email'],
            'mobile' => $post['mobile']
        );
        $userModel = D('Todo/Sys/User');
        $newpassword = $post['newpassword'];
        if($newpassword){
            if($newpassword != $post['repassword']) {
                $this->setError("新密码和确认密码不一致!");
                return false;
            }
            $userInfo = $userModel->keyFind($userId);
            $data['password'] = LoginService::getInstance()->encrypt($newpassword, $userInfo['salt']);
        }

        return $userModel->where(array('id'=>$userId))->save($data);
    }

    /**
     * 查询一个用户的角色
     * @param $userId 用户ID
     * @param bool $onlyIds 返回逗号隔开的角色ID字符串
     * @return bool|string|array
     */
    public function getUserRole($userId, $onlyIds=false){
        $list = D('Todo/Sys/UserRole')->where(array('user_id'=>$userId))->select();
        if(!$list) return false;

        $list = ArrayUtil::getColumn($list, 'role_id');
        if($onlyIds) return implode(',', $list);
        return $list;
    }

    /**
     * 按用户查询有权限的应用
     * @param int $userId
     * @return false|mixed|array
     */
    public function getUserApp($userId=0){
        //默认当前登录用户
        if(!$userId) $userId = LoginService::getInstance()->getCurrentUser('id');

        //超级管理员
        if(LoginService::getInstance()->checkSuper($userId)) return D('Todo/Sys/Application')->select();
        //else var_dump(C('AUTH.SUPER_USER'));echo  $userId;
        $roleList = $this->getUserRole($userId, true);
        $menuList = D('Todo/Sys/RoleMenu')->where(array('role_id'=>array('in', $roleList)))->getField('menu_id');
        $appIdArr = D('Todo/Sys/Menu')->where(array('menu_id'=>array('in', $menuList)))->getField('app_id');
        return D('Todo/Sys/Application')->where(array('status'=>1, 'id'=>array('in', $appIdArr)))->select();
    }

    /**
     * 基于一级缓存的用户查询
     * @param $userId
     * @param bool $field
     */
    public function cacheFindUser($userId, $field=true){
        $userInfo = self::$CACHES[$userId];
        if(!$userInfo){
            $userInfo = D('Todo/Sys/User')->keyFind($userId);
            self::$CACHES[$userId][$userId] = $userInfo;
        }
        if(!$userInfo) return null;
        return $field===true ? $userInfo : $userInfo[$field];
    }
}